package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.BaseService;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.CardBusinessQuotesConstant;
import com.aiti.lulian.dto.CardBusinessQuotesDto;
import com.aiti.lulian.dto.CardBusinessQuotesProductDto;
import com.aiti.lulian.dto.CardQuoteListDto;
import com.aiti.lulian.dto.CardBusinessQuotesDto;
import com.aiti.lulian.dto.CardBusinessQuotesProductDto;
import com.aiti.lulian.entity.CardEnterpriseTemplate;
import com.aiti.lulian.entity.CustomerManagement;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.crad.CardBusinessQuotes;
import com.aiti.lulian.entity.crad.CardBusinessQuotesProduct;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.ICardBusinessQuotesProductService;
import com.aiti.lulian.service.ICardBusinessQuotesService;
import com.aiti.lulian.utils.DateFilterUtil;
import com.aiti.lulian.vo.CardQuoteVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.aiti.lulian.vo.CardBusinessQuotesProductVo;
import com.aiti.lulian.vo.CardBusinessQuotesVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import java.util.List;

@Service
public class CardBusinessQuotesServiceImpl extends BaseSerivceImpl<CardBusinessQuotesMapper, CardBusinessQuotes> implements ICardBusinessQuotesService {

    private final CardBusinessQuotesMapper cardBusinessQuotesMapper;

    private final CustomerManagementMapper customerManagementMapper;

    private final LuLianEnterpriseMapper luLianEnterpriseMapper;

    private final ICardBusinessQuotesProductService creditCardBusinessQuotesProductService;

    public CardBusinessQuotesServiceImpl(CardBusinessQuotesMapper cardBusinessQuotesMapper,
                                         ICardBusinessQuotesProductService creditCardBusinessQuotesProductService,
                                         CustomerManagementMapper customerManagementMapper,
                                         LuLianEnterpriseMapper luLianEnterpriseMapper) {
        this.cardBusinessQuotesMapper = cardBusinessQuotesMapper;
        this.creditCardBusinessQuotesProductService = creditCardBusinessQuotesProductService;
        this.customerManagementMapper = customerManagementMapper;
        this.luLianEnterpriseMapper = luLianEnterpriseMapper;
    }



    /**
     * 保存名片报价单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCardBusinessQuotes(CardBusinessQuotesDto dto,String userId) {

//        String clientId = dto.getClientId();

        //如果不是UUID,再次判断是否是汉字
//        if(ReUtil.isMatch("[\\u4e00-\\u9fa5]+", clientId)){
//            //这里创建一个客户
//            //查询企业名称
//            String enterpriseId = dto.getEnterpriseId();
//            QueryWrapper<LuLianEnterprise> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("base_id",enterpriseId);
//            queryWrapper.select("base_name");
//            LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectOne(queryWrapper);
//            if(luLianEnterprise == null){
//                throw new RuntimeException("没有找到企业信息");
//            }
//            String id = IdUtil.simpleUUID();
//            //新增的客户ID为潜在客户
//            CustomerManagement customerManagement = CustomerManagement.builder()
//                    .baseId(id)
//                    .isDel("0")
//                    .customerStatusId("fffdd190ca55471cbfe789f89259d63e01")
//                    .baseCreateTime(new Date())
//                    .enterpriseName(luLianEnterprise.getBaseName())
//                    .saleResponsiblePerson(userId)
//                    .contacts(clientId)
//                    .companyId(dto.getEnterpriseId())
//                    .build();
//            customerManagementMapper.insert(customerManagement);
//            dto.setClientId(id);
//        }
        BigDecimal discountPercentage = dto.getDiscountPercentage();
        if(discountPercentage != null && discountPercentage.stripTrailingZeros().scale() > 0){
            throw new RuntimeException("折扣不能为小数");
        }

        CardBusinessQuotes cardBusinessQuotes = new CardBusinessQuotes();
        BeanUtil.copyProperties(dto,cardBusinessQuotes,"productList");
        cardBusinessQuotes.setBaseId(IdUtil.simpleUUID());
        cardBusinessQuotes.setBaseCreateBy(userId);

        List<CardBusinessQuotesProductDto> productList = dto.getProductList();
        if(productList != null && productList.size() > 0){
            long count = productList.stream().filter(item -> {
                BigDecimal price = item.getPrice();
                Long productCount = item.getProductCount();

                if (price == null || productCount == null) {
                    return true;
                }

                if (price.compareTo(BigDecimal.ZERO) <= 0 || productCount <= 0) {
                    return true;
                }
                if(price.stripTrailingZeros().scale() > 2){
                    return true;
                }
                return false;
            }).count();
            if(count > 0){
                throw new RuntimeException("产品数据存在异常【价格、数量不能为0,价格最多保留两位小数】");
            }
            List<CardBusinessQuotesProduct> collect = productList.stream().map(item -> productDtoConvertProduct(item,dto.getDiscountPercentage(),cardBusinessQuotes.getBaseId())).collect(Collectors.toList());
            //计算所有的产品总价
            BigDecimal productTotalPrice = collect.stream().map(CardBusinessQuotesProduct::getTotalPrice).reduce(BigDecimal::add).get();
            BigDecimal totalPrice = cardBusinessQuotes.getTotalPrice();
            if(totalPrice != null && totalPrice.compareTo(productTotalPrice) != 0){
                cardBusinessQuotes.setTotalPrice(totalPrice);
            }else{
                cardBusinessQuotes.setTotalPrice(productTotalPrice);
            }

            creditCardBusinessQuotesProductService.saveBatch(collect);
        }

        cardBusinessQuotes.setBaseUpdateTime(new Date());
        cardBusinessQuotes.setBaseCreateTime(new Date());
        cardBusinessQuotesMapper.insert(cardBusinessQuotes);
    }

    /**
     * 通过Id查询报价单
     *
     * @param quotesId
     * @return
     */
    @Override
    public CardBusinessQuotesVo queryQuotesProductById(String quotesId) {
        CardBusinessQuotes cardBusinessQuotes = cardBusinessQuotesMapper.selectById(quotesId);
        CardBusinessQuotesVo cardBusinessQuotesVo = new CardBusinessQuotesVo();
        if(cardBusinessQuotes == null){
            return cardBusinessQuotesVo;
        }
        BeanUtil.copyProperties(cardBusinessQuotes, cardBusinessQuotesVo);

        LambdaQueryWrapper<CardBusinessQuotesProduct> lqw = new LambdaQueryWrapper<CardBusinessQuotesProduct>();

        List<CardBusinessQuotesProduct> list = creditCardBusinessQuotesProductService.list(lqw);

        if(list != null && list.size() > 0){
            List<CardBusinessQuotesProductVo> collect = list.stream().map(this::productEntityToProductVo).collect(Collectors.toList());
            cardBusinessQuotesVo.setProductList(collect);
        }

        return cardBusinessQuotesVo;
    }

    /**
     * 更新报价单
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateQuotesById(CardBusinessQuotesDto dto,String userId) {
        BigDecimal discountPercentage = dto.getDiscountPercentage();
        if(discountPercentage != null && discountPercentage.stripTrailingZeros().scale() > 0){
            throw new RuntimeException("折扣不能为小数");
        }
        CardBusinessQuotes cardBusinessQuotes = new CardBusinessQuotes();
        BeanUtil.copyProperties(dto,cardBusinessQuotes,"productList");

        List<CardBusinessQuotesProductDto> productList = dto.getProductList();
        //删除所有的产品
        creditCardBusinessQuotesProductService.remove(new QueryWrapper<CardBusinessQuotesProduct>().eq("quote_id",dto.getBaseId()));
        if(productList != null && productList.size() > 0){
            long count = productList.stream().filter(item -> {
                BigDecimal price = item.getPrice();
                Long productCount = item.getProductCount();

                if (price == null || productCount == null) {
                    return true;
                }

                if (price.compareTo(BigDecimal.ZERO) <= 0 || productCount <= 0) {
                    return true;
                }
                if(price.stripTrailingZeros().scale() > 2){
                    return true;
                }
                return false;
            }).count();
            if(count > 0){
                throw new RuntimeException("产品数据存在异常【价格、数量不能为0,价格最多保留两位小数】");
            }
            List<CardBusinessQuotesProduct> collect = productList.stream().map(item -> productDtoConvertProduct(item,dto.getDiscountPercentage(),cardBusinessQuotes.getBaseId())).collect(Collectors.toList());
            //计算所有的产品总价
            BigDecimal productTotalPrice = collect.stream().map(CardBusinessQuotesProduct::getTotalPrice).reduce(BigDecimal::add).get();
            BigDecimal totalPrice = cardBusinessQuotes.getTotalPrice();
            if(totalPrice != null && totalPrice.compareTo(productTotalPrice) != 0){
                cardBusinessQuotes.setTotalPrice(totalPrice);
            }

            creditCardBusinessQuotesProductService.saveBatch(collect);
        }
        cardBusinessQuotes.setBaseUpdateTime(new Date());
        cardBusinessQuotes.setBaseUpdateBy(userId);
        cardBusinessQuotesMapper.updateById(cardBusinessQuotes);
    }

    /**
     * 删除报价单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQuotesById(CardBusinessQuotesDto dto) {
        cardBusinessQuotesMapper.deleteById(dto.getBaseId());
        creditCardBusinessQuotesProductService.remove(new QueryWrapper<CardBusinessQuotesProduct>().eq("quote_id",dto.getBaseId()));
    }

    /**
     * 实体类转换成Vo类
     * @param cardBusinessQuotesProduct
     * @return
     */
    private CardBusinessQuotesProductVo productEntityToProductVo(CardBusinessQuotesProduct cardBusinessQuotesProduct) {
        CardBusinessQuotesProductVo productVo = new CardBusinessQuotesProductVo();
        BeanUtil.copyProperties(cardBusinessQuotesProduct,productVo);
        return productVo;
    }

    /**
     * 将dto中的产品转换成实体类的数据
     * @param dto
     * @param zk
     * @return
     */
    private CardBusinessQuotesProduct productDtoConvertProduct(CardBusinessQuotesProductDto dto, BigDecimal zk,String quotesId){
        CardBusinessQuotesProduct temp = new CardBusinessQuotesProduct();
        BeanUtil.copyProperties(dto,temp);

        temp.setQuoteId(quotesId);
        temp.setBaseId(IdUtil.simpleUUID());
        temp.setBaseCreateTime(new Date());
        temp.setBaseUpdateTime(new Date());
        //计算总数
        BigDecimal price = temp.getPrice();
        Long productCount = temp.getProductCount();

        BigDecimal priceCount = price.multiply(BigDecimal.valueOf(productCount));
        priceCount = priceCount.setScale(2, BigDecimal.ROUND_HALF_UP);

        if(zk != null && zk.compareTo(BigDecimal.ZERO) > 0){
            BigDecimal divide = zk.divide(new BigDecimal("100"));
            BigDecimal totalPrice = priceCount.multiply(divide);
            temp.setTotalPrice(totalPrice);
        }else{
            temp.setTotalPrice(priceCount);
        }
        return temp;
    }

    @Autowired
    private CardBusinessQuotesProductMapper cardBusinessQuotesProductMapper;

    @Override
    public List<CardQuoteListDto> queryQuotePage(Page<CardBusinessQuotes> page, CardQuoteVo quote) {
        String type = quote.getType();
        String enterpriseId = quote.getEnterpriseId();
        String roleId = quote.getRoleId();
        String dateFilterType = quote.getDateFilterType();
        if(!StringUtils.isEmpty(dateFilterType)){
            Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
            quote.setBeginDate(beginAndEnd.get("begin"));
            quote.setEndDate(beginAndEnd.get("end"));
        }
        /**
         * 企业管理者：员工所有的报价单+企业所有员工收到的报价单
         * 企业员工：自己创建的报价单+自己收到的报价单
         * 没绑定企业的：自己收到的报价单
         */
        if(StrUtil.equalsAny(type, CardBusinessQuotesConstant.MY_QUOTE, CardBusinessQuotesConstant.RECEIVED_QUOTE, CardBusinessQuotesConstant.ALL_QUOTE)){
            if(CardBusinessQuotesConstant.ALL_QUOTE.equals(type)){
                quote.setDataType(quote.getType());
                if(StringUtils.isEmpty(enterpriseId) && CardBusinessQuotesConstant.ALL_QUOTE.equals(type)){
                    //如果用户没有关联企业，选择所有时查询自己接收的报价单
                    quote.setType(null);
                    quote.setDataType(CardBusinessQuotesConstant.RECEIVED_QUOTE);
                }
                if(!StringUtils.isEmpty(roleId)){
                    String[] roleIds = roleId.split(StrUtil.COMMA);
                    //认证企业
                    long enterpriseManageCount = Arrays.stream(roleIds).filter(f -> f.equals(CardBusinessQuotesConstant.AUTHENTICATION_ENTERPRISE_ROLE)).count();
                    //企业员工
                    long enterpriseUserCount = Arrays.stream(roleIds).filter(f -> f.equals(CardBusinessQuotesConstant.ENTERPRISE_USER_ROLE)).count();
                    if(enterpriseUserCount > 0){
                        quote.setDataType(CardBusinessQuotesConstant.MY_AND_RECEIVE_QUOTE);
                    }
                    if(enterpriseManageCount > 0){
                        quote.setDataType(CardBusinessQuotesConstant.ENTERPRISE_AND_ENTERPRISE_RECEIVE_QUOTE);
                    }


                }else{
                    //如果用户没有关联企业，选择所有时查询自己接收的报价单
                    quote.setType(null);
                    quote.setDataType(CardBusinessQuotesConstant.RECEIVED_QUOTE);
                }
            }

            return cardBusinessQuotesMapper.queryQuotePage(page, quote);
        }else{
            return new ArrayList<CardQuoteListDto>();
        }

    }

    @Override
    public CardBusinessQuotesDto quoteDetail(String id) {
        CardBusinessQuotesDto quoteDto = cardBusinessQuotesMapper.quoteDetail(id);
        if(quoteDto != null){
            List<CardBusinessQuotesProductDto> cardBusinessQuotesProductDtos = cardBusinessQuotesProductMapper.productList(id);
            quoteDto.setProductList(cardBusinessQuotesProductDtos);
        }
        return quoteDto;
    }
}
